package com.mobiusws.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfUtil extends ExportingUtil
{

	public static String ConvertDate(String strDate) {
		
		String strRe = null;
		
		int ilen = strDate.length();
		if(ilen==8) //day
		{
			SimpleDateFormat inFormat = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
			
			try {
				Date inDate = inFormat.parse(strDate);
				
				strRe = outFormat.format(inDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			
		}
		else if(ilen>8 && ilen<=12)
		{
			SimpleDateFormat inFormat = new SimpleDateFormat("yyyyMMddHH");
			SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			try {
				Date inDate = inFormat.parse(strDate);
				
				strRe = outFormat.format(inDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else if(ilen == 14) {
			SimpleDateFormat inFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			try {
				Date inDate = inFormat.parse(strDate);
				
				strRe = outFormat.format(inDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			strRe = strDate;
		}
			
		return strRe;
	}
	
	public  void convert(ExportReport reportStruct, String strCountryCode, long maskBits, ResultSet rs, int cols, int rows, float[] fSheetColumnWidthArray, String strOutPdfFile)
	{
		
		File outPdfFile = new File(strOutPdfFile);
		try
		{
			outPdfFile.createNewFile();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		try
		{
			//get the info from the excel file
			float[] fTableArray = new float[cols];
			float myPageWidth=0.0f;
			float myPageHeight=595.0f;
			for (int i = 0; i < cols; i++)
			{
				fTableArray[i] = fSheetColumnWidthArray[i] / 38.0f;
				myPageWidth += fTableArray[i];
			}
			myPageWidth+=100.0f; //empty side
			
			//start to generate the pdf
			Rectangle rectPageSize = new RectangleReadOnly(myPageHeight, myPageWidth);//
			rectPageSize = rectPageSize.rotate();
			Document doc = new Document(rectPageSize, 50, 50, 50, 50);
			
			PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outPdfFile.getAbsolutePath()));
			
			writer.setBoxSize("pagebox", new Rectangle(50, 50, myPageWidth, myPageHeight));
            HeaderFooter event = new HeaderFooter();
            writer.setPageEvent(event);
            
			BaseFont baseFont = BaseFont.createFont();
			Font defaultFont = new Font(baseFont, 12, Font.NORMAL);
			Font redFont = new Font(baseFont, 12, Font.NORMAL);
			redFont.setColor(BaseColor.RED);
			doc.open();
			
			PdfPTable pdfTable = new PdfPTable(cols);
			pdfTable.setComplete(false);
			//pdfTable.setWidthPercentage(fTableArray, rectPageSize);
			pdfTable.setHorizontalAlignment(Element.ALIGN_LEFT);
			pdfTable.setTotalWidth(fTableArray);
			pdfTable.setLockedWidth(true);

			//System.out.println("rectPageSize=" + rectPageSize.getWidth());
			PdfPCell pdfCell = null;

			// add the logo
			int iRow = 0;
			Image im = Image.getInstance("/opt/GK2/portal/resource/logo.png");
			im.setRotationDegrees(30);
			im.setRotationDegrees(0);

			pdfCell = new PdfPCell();
			pdfCell.setColspan(cols);
			pdfCell.setFixedHeight(25f);
			pdfCell.setHorizontalAlignment(Element.ALIGN_LEFT);
			pdfCell.setImage(im);
			pdfCell.setNoWrap(true);
			pdfTable.addCell(pdfCell);
			iRow++;

			//defaultFont.setColor(BaseColor.BLACK);
			// add the report name and date
			pdfCell = makeCell(reportStruct.getReportName(), cols, Element.ALIGN_LEFT, 1, defaultFont);
			pdfCell.setNoWrap(true);
			pdfTable.addCell(pdfCell);
			iRow++;

			pdfCell = makeCell(ConvertDate(reportStruct.getReportDate()), cols, Element.ALIGN_LEFT, 1, defaultFont);
			pdfCell.setNoWrap(true);
			pdfTable.addCell(pdfCell);
			iRow++;

			String content;
			//defaultFont.setColor(BaseColor.WHITE);
			for (int j = 0; j < cols; j++)
			{
				content = reportStruct.getReportTitleArray()[j];
				pdfCell = makeCell(content, 1, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
			}
			iRow++;

			doc.add(pdfTable);
			
			if (rows > 0)
			{
				pdfCell.setBackgroundColor(BaseColor.WHITE);
				defaultFont.setColor(BaseColor.BLACK);

				int curRow = 0;
				String msisdn =  "";
				try
				{
					
					while (rs.next())
					{

						for (int i = 0; i < cols; i++)
						{
							if(reportStruct.getReportDate().length()==10 && ("suspect".compareTo(reportStruct.getReportName())==0 || "simbox".compareTo(reportStruct.getReportName())==0) && "verify".compareToIgnoreCase(reportStruct.getTableColumnsArray()[i])==0) //hourly verify convert
							{
								String strTemp;
								int iVerify = rs.getInt(i + 1);
								if(iVerify==1)
								{
									strTemp="F";
								}
								else if(iVerify==2)
								{
									strTemp="V";
								}
								else
								{
									strTemp="O";
								}
								pdfCell = makeCell(strTemp, 1, Element.ALIGN_LEFT, 1, defaultFont);
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if(reportStruct.getTableColumnsArray()[i].indexOf("odds")>=0 || reportStruct.getTableColumnsArray()[i].indexOf("off_peak")>=0) //percentage
							{
								pdfCell = makeCell(String.format("%.2f", rs.getFloat(i + 1)*100.0f)+"%", 1, Element.ALIGN_LEFT, 1, defaultFont);
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if(reportStruct.getTableColumnsArray()[i].indexOf("msisdn")>=0 && !reportStruct.getTableColumnsArray()[i].startsWith("msisdn_f"))  
							{
								msisdn = rs.getString(i + 1);
								String[] strArray = ExportingUtil.getStringAndFlagArray(msisdn, reportStruct);
								msisdn = strArray[0];
								String msisdn_f = strArray[1];
								

								if(maskBits>0) //unmask the msisdn
								{
									msisdn = intXORMask(msisdn, maskBits);
								}
								if ("1".equals(msisdn_f)) {
									pdfCell = makeCell(msisdn, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(msisdn, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
								
							}
							else if("imei".equals(reportStruct.getTableColumnsArray()[i].trim()))
							{
								String[] strArray = ExportingUtil.getStringAndFlagArray(rs.getString(i + 1), reportStruct);
								String imei = strArray[0];
								String imei_f = strArray[1];
								if ("1".equals(imei_f)) {
									pdfCell = makeCell(imei, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(imei, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if("imsi".equals(reportStruct.getTableColumnsArray()[i].trim()))
							{
								String[] strArray = ExportingUtil.getStringAndFlagArray(rs.getString(i + 1), reportStruct);
								String imsi = strArray[0];
								String imsi_f = strArray[1];
								if ("1".equals(imsi_f)) {
									pdfCell = makeCell(imsi, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(imsi, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if("cell_id".equals(reportStruct.getTableColumnsArray()[i].trim()))
							{
								String[] strArray = ExportingUtil.getStringAndFlagArray(rs.getString(i + 1), reportStruct);
								String cell_id = strArray[0];
								String cell_id_f = strArray[1];
								if ("1".equals(cell_id_f)) {
									pdfCell = makeCell(cell_id, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(cell_id, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else
							{
								pdfCell = makeCell(rs.getString(i + 1), 1, Element.ALIGN_LEFT, 1, defaultFont);
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
						}

						curRow++;

						if (curRow % 1000 == 0)
						{
							doc.add(pdfTable);
						}
					}
					
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			pdfTable.setComplete(true);
			doc.add(pdfTable);
			doc.close();
			
			writer.flush();
            writer.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.out.println("Create PDF File failed.");
		}
	}
	
	public static PdfPCell makeCell(String content, int colspan, int align, int maxLines, Font font)
	{
		PdfPCell cell = null;
		Paragraph paragraph = null;
		try
		{
			// set Font
			paragraph = new Paragraph(content, font);
			cell = new PdfPCell(paragraph);
			// set colspan and set rowspan
			if (colspan > 1)
			{
				cell.setColspan(colspan);
			}
			// set HorizontalAlignment
			cell.setHorizontalAlignment(align);

			// set maxlines
			cell.setRowspan(maxLines);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return cell;
	}
	
	public  void convert(ExportReport reportStruct, String strCountryCode, long maskBits, List<List<Object>> ls, int cols, int rows, float[] fSheetColumnWidthArray, String strOutPdfFile)
	{
		File outPdfFile = new File(strOutPdfFile);
		try
		{
			outPdfFile.createNewFile();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		try
		{
			//get the info from the excel file
			float[] fTableArray = new float[cols];
			float myPageWidth=0.0f;
			float myPageHeight=595.0f;
			for (int i = 0; i < cols; i++)
			{
				fTableArray[i] = fSheetColumnWidthArray[i] / 38.0f;
				myPageWidth += fTableArray[i];
			}
			myPageWidth+=100.0f; //empty side
			
			//start to generate the pdf
			Rectangle rectPageSize = new RectangleReadOnly(myPageHeight, myPageWidth);//
			rectPageSize = rectPageSize.rotate();
			Document doc = new Document(rectPageSize, 50, 50, 50, 50);
			
			PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outPdfFile.getAbsolutePath()));
			
			writer.setBoxSize("pagebox", new Rectangle(50, 50, myPageWidth, myPageHeight));
            HeaderFooter event = new HeaderFooter();
            writer.setPageEvent(event);
            
			BaseFont baseFont = BaseFont.createFont();
			Font defaultFont = new Font(baseFont, 12, Font.NORMAL);
			Font redFont = new Font(baseFont, 12, Font.NORMAL);
			redFont.setColor(BaseColor.RED);
			doc.open();
			
			PdfPTable pdfTable = new PdfPTable(cols);
			pdfTable.setComplete(false);
			//pdfTable.setWidthPercentage(fTableArray, rectPageSize);
			pdfTable.setHorizontalAlignment(Element.ALIGN_LEFT);
			pdfTable.setTotalWidth(fTableArray);
			pdfTable.setLockedWidth(true);

			//System.out.println("rectPageSize=" + rectPageSize.getWidth());
			PdfPCell pdfCell = null;

			// add the logo
			int iRow = 0;
			Image im = Image.getInstance("/opt/GK2/portal/resource/logo.png");
			im.setRotationDegrees(30);
			im.setRotationDegrees(0);

			pdfCell = new PdfPCell();
			pdfCell.setColspan(cols);
			pdfCell.setFixedHeight(25f);
			pdfCell.setHorizontalAlignment(Element.ALIGN_LEFT);
			pdfCell.setImage(im);
			pdfCell.setNoWrap(true);
			pdfTable.addCell(pdfCell);
			iRow++;
			
			if(reportStruct.getReportName().indexOf("weekly") >= 0 || reportStruct.getReportName().indexOf("Hourly") >= 0 ) {
				//defaultFont.setColor(BaseColor.BLACK);
				// add the report name and date
				pdfCell = makeCell(reportStruct.getReportName(), cols, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
				iRow++;

				pdfCell = makeCell(ConvertDate(reportStruct.getReportDate()), cols, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
				iRow++;
			} else {
				//defaultFont.setColor(BaseColor.BLACK);
				// add the report name and date
				pdfCell = makeCell("User:" + reportStruct.getReportName(), cols, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
				iRow++;
	
				pdfCell = makeCell("Extraction time:" + ConvertDate(reportStruct.getReportDate()), cols, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
				iRow++;
				
				//add by wilson
				pdfCell = makeCell("Criteria:" + ConvertDate(reportStruct.getQueryCriteria()), cols, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
				iRow++;
				//add by wilson
			}
			String content;
			//defaultFont.setColor(BaseColor.WHITE);
			for (int j = 0; j < cols; j++)
			{
				content = reportStruct.getReportTitleArray()[j];
				pdfCell = makeCell(content, 1, Element.ALIGN_LEFT, 1, defaultFont);
				pdfCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
				pdfCell.setNoWrap(true);
				pdfTable.addCell(pdfCell);
			}
			iRow++;

			doc.add(pdfTable);
			
			if (rows > 0)
			{
				pdfCell.setBackgroundColor(BaseColor.WHITE);
				defaultFont.setColor(BaseColor.BLACK);

				int curRow = 0;
				String msisdn =  "";
				List<Object> ob = null;
				
				try {
					for(int l = 0; l < ls.size(); l++)
					{
						ob = ls.get(l);

						for (int i = 0; i < cols; i++)
						{
							if(reportStruct.getTableColumnsArray()[i].indexOf("odds")>=0 || reportStruct.getTableColumnsArray()[i].indexOf("off_peak")>=0) //percentage
							{
								pdfCell = makeCell(String.format("%.2f", Float.parseFloat(ob.get(i).toString())*100.0f)+"%", 1, Element.ALIGN_LEFT, 1, defaultFont);
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if(reportStruct.getTableColumnsArray()[i].indexOf("msisdn")>=0 && !reportStruct.getTableColumnsArray()[i].startsWith("msisdn_f"))  
							{
								msisdn = ob.get(i).toString();
								String[] strArray = ExportingUtil.getStringAndFlagArray(msisdn, reportStruct);
								msisdn = strArray[0];
								String msisdn_f = strArray[1];

								if(maskBits>0) //unmask the msisdn
								{
									msisdn = intXORMask(msisdn, maskBits);
								}
								if ("1".equals(msisdn_f)) {
									pdfCell = makeCell(msisdn, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(msisdn, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
								
							}
							else if("imei".equals(reportStruct.getTableColumnsArray()[i].trim()))
							{
								String[] strArray = ExportingUtil.getStringAndFlagArray(ob.get(i).toString(), reportStruct);
								String imei = strArray[0];
								String imei_f = strArray[1];
								if ("1".equals(imei_f)) {
									pdfCell = makeCell(imei, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(imei, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if("imsi".equals(reportStruct.getTableColumnsArray()[i].trim()))
							{
								String[] strArray = ExportingUtil.getStringAndFlagArray(ob.get(i).toString(), reportStruct);
								String imsi = strArray[0];
								String imsi_f = strArray[1];
								if ("1".equals(imsi_f)) {
									pdfCell = makeCell(imsi, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(imsi, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else if("cell_id".equals(reportStruct.getTableColumnsArray()[i].trim()))
							{
								String[] strArray = ExportingUtil.getStringAndFlagArray(ob.get(i).toString(), reportStruct);
								String cell_id = strArray[0];
								String cell_id_f = strArray[1];
								if ("1".equals(cell_id_f)) {
									pdfCell = makeCell(cell_id, 1, Element.ALIGN_LEFT, 1, redFont);
								} else {
									pdfCell = makeCell(cell_id, 1, Element.ALIGN_LEFT, 1, defaultFont);
								}
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
							else
							{
								pdfCell = makeCell(ob.get(i).toString(), 1, Element.ALIGN_LEFT, 1, defaultFont);
								pdfCell.setNoWrap(true);
								pdfTable.addCell(pdfCell);
							}
						}

						curRow++;

						if (curRow % 1000 == 0)
						{
							doc.add(pdfTable);
						}
					}
					
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			pdfTable.setComplete(true);
			doc.add(pdfTable);
			doc.close();
			
			writer.flush();
            writer.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.out.println("Create PDF File failed.");
		}
	}

	
}
